package com.wlyuan.index.domain.index.repository;


import com.wlyuan.core.domain.valueobj.WaybillId;
import com.wlyuan.index.domain.index.WaybillIndex;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author yuanjie
 */
public interface WaybillIndexRepository extends ElasticsearchRepository<WaybillIndex, Long> {
    default WaybillIndex ofId(WaybillId waybillId) {
        return this.findById(waybillId.getId()).orElse(null);
    }

    default Map<WaybillId, WaybillIndex> indexes(Collection<WaybillId> waybillIds) {
        if (CollectionUtils.isEmpty(waybillIds)) {
            return Collections.emptyMap();
        }
        var ids = waybillIds.stream()
                .map(WaybillId::getId)
                .collect(Collectors.toList());
        var indexes = this.findAllById(ids);
        return StreamSupport.stream(indexes.spliterator(), false)
                .parallel()
                .collect(Collectors.toMap(index -> new WaybillId(index.getWaybillId()), index -> index));
    }
}
